package com.zxy.lm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zxy.lm.DO.BorrowRecordDO;
import com.zxy.lm.entity.BorrowRecord;
import com.zxy.lm.mapper.BorrowRecordMapper;
import com.zxy.lm.service.BookService;
import com.zxy.lm.service.BorrowRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zxy.lm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author jiusi
 * @since 2021-06-22
 */
@Service
public class BorrowRecordServiceImpl extends ServiceImpl<BorrowRecordMapper, BorrowRecord> implements BorrowRecordService {

    @Autowired
    private BorrowRecordMapper borrowRecordMapper;

    @Autowired
    private BookService bookService;

    @Autowired
    private UserService userService;

    @Override
    public boolean selectExistenceNotReturned(Integer userId) {
        LocalDateTime dateTime = borrowRecordMapper.selectLastReturnTime(userId);
        return dateTime == null;
    }

    @Override
    public List<BorrowRecord> getAllRecordByUserId(Integer userId) {
        QueryWrapper<BorrowRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        return baseMapper.selectList(queryWrapper);
    }

    @Override
    public List<BorrowRecordDO> getAllRecordDOByUserId(Integer userId) {
        return borrowRecordMapper.selectAllRecordDOByUserId(userId);
    }

//    @Override
//    @Transactional
//    public boolean borrow(Integer userId, Integer bookId, Integer days) {
//        BorrowRecord borrowRecord = new BorrowRecord();
//        borrowRecord.setId(null)
//                .setUserId(userId)
//                .setBookId(bookId)
//                .setStartTime(LocalDateTime.now())
//                .setEndTime(LocalDateTime.now().plusDays(days))
//                .setReturnTime(null);
//
//        //查询是否存在未归还的借书记录
//        boolean notReturned = selectExistenceNotReturned(userId);
//        if (notReturned) {
//            //存在未归还则不能借书
//            return false;
//        }
//
//        boolean a = save(borrowRecord);
//        boolean b = bookService.decreaseBookStock(bookId, 1);
//        return a && b;
//    }

//    @Override
//    @Transactional
//    public boolean returnBook(Integer recordId, Integer userID) {
//
//        //已经有还书时间
//        LocalDateTime time = borrowRecordMapper.selectReturnTime(recordId);
//        if (time != null) {
//            return false;
//        }
//
//        BorrowRecord borrowRecord = new BorrowRecord();
//        //设置还书时间
//        borrowRecord.setReturnTime(LocalDateTime.now());
//        QueryWrapper<BorrowRecord> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("id", recordId);
//        queryWrapper.eq("user_id", userID);
//        int update = borrowRecordMapper.update(borrowRecord, queryWrapper);
//        int bookId = borrowRecordMapper.getBookIdById(recordId);
//
//        //添加图书库存
//        boolean b = bookService.increaseBookStock(bookId, 1);
//
//        return update > 0 && b;
//    }

    @Override
    @Transactional
    public boolean addBorrowRecord(String username, Integer bookId, Integer days, Integer adminId) {
        Integer userId = userService.getUserIdByUsername(username);
        //没有查找到用户id，说明账号错误
        if (null == userId) {
            return false;
        }
        Integer count = bookService.getBookStockById(bookId);
        //数量小于1，没有库存，借阅失败
        if (count < 1) {
            return false;
        }
        //构造新的借书记录
        BorrowRecord borrowRecord = new BorrowRecord();
        borrowRecord.setId(null)
                .setUserId(userId)
                .setBookId(bookId)
                .setStartTime(LocalDateTime.now())
                .setEndTime(LocalDateTime.now().plusDays(days))
                .setReturnTime(null)
                .setAdminId(adminId);
        //添加借书记录
        int i = borrowRecordMapper.insert(borrowRecord);
        //减少1个图书库存
        boolean b = bookService.decreaseBookStock(bookId, 1);
        return i > 0 & b;
    }

    @Override
    @Transactional
    public boolean returnBook(Integer recordId) {
        //通过id查找记录
        QueryWrapper<BorrowRecord> queryWrapper = new QueryWrapper<BorrowRecord>().eq("id", recordId);
        BorrowRecord record = borrowRecordMapper.selectOne(queryWrapper);
        //记录中有返回时间说明已返还
        if (null != record.getReturnTime()) {
            return false;
        }
        //添加还书时间
        record.setReturnTime(LocalDateTime.now());
        //更新记录
        int i = borrowRecordMapper.updateById(record);
        //增加1个图书库存
        boolean b = bookService.increaseBookStock(record.getBookId(), 1);
        return i > 0 && b;
    }

    @Override
    public String getRecordUsernameById(Integer recordId) {
        return borrowRecordMapper.selectRecordUsernameById(recordId);
    }


}
